import React from 'react';
import {connect} from 'dva';
import { Accordion, List, NavBar, Icon, Button, Modal, Toast, Switch, InputItem, DatePicker, Picker } from 'antd-mobile';
import addTraveller from '@/components/addTraveller';
import addAdvanceInfoModal from '@/components/addAdvanceInfo';
import ScModal from '@/components/searchCity';
import styles from './index.less';
import { getNameByData, getMastId, requestSuccess } from '@/utils/tools';
import UserServices from '@/services/user';

/**
 * 出差详情
 */
class cTravelDetails extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      datepickerActiveKey: '',
      datepickerVisible: false
    }
  }

  handleAddTraveler = () => {
    addTraveller.open({
      isOutboundTrip: this.props.detail.mast.isOutboundTrip == 'YES'?true:false,
      companyCode: this.props.detail.mast.companyCode,
      dptrDay: this.props.detail.mast.dptrDay,
      rtnDay: this.props.detail.mast.rtnDay,
      success: (travellers) => {
        this.props.dispatch({type: 'detail/changeDetail', payload: {
          allMobileTravelerList: travellers
        }})
      }
    })
  }

  handleEditTravelerWbsCode = (e, item, index) => {
    e.stopPropagation();
    addTraveller.open({
      isOutboundTrip: this.props.detail.mast.isOutboundTrip == 'YES'?true:false,
      companyCode: this.props.detail.mast.companyCode,
      dptrDay: this.props.detail.mast.dptrDay,
      rtnDay: this.props.detail.mast.rtnDay,
      editWbsInfo: {
        empNo: item.empNo,
        chargeEmpNo: item.chargeEmpNo,
        travelerId: item.id
      },
      success: (travellers) => {
        this.props.dispatch({type: 'detail/changeDetail', payload: {
          allMobileTravelerList: travellers
        }})
      }
    })
  }

  handleAddAdvanceInfo = () => {
    addAdvanceInfoModal.open({
      companyCode: this.props.detail.mast.companyCode,
      success: (data) => {
        this.props.dispatch({type: 'detail/changeDetail', payload: {
          advanceInfo: this.props.detail.advanceInfo.concat(data)
        }})
      }
    });
  }

  handleShowDatePicker = (activeKey) => {
    if(!this.props.edit)return;
    this.setState({
      datepickerActiveKey: activeKey,
      datepickerVisible: true
    })
  }

  handleSaveDatepickerValue = (date) => {
    if(this.state.datepickerActiveKey){
      this.onChange(global.moment(date).format('YYYY-MM-DD').valueOf(), this.state.datepickerActiveKey);
      this.setState({
        datepickerVisible: false
      })
    }
  }

  handleListLabel = (list) => {
    return global._.map(list, item => {
      return {
        label: item,
        value: item
      }
    });
  }

  handleShowCities = (key) => {
    // this.props.history.push('/searchCity');
    ScModal.open({
      success: (data)=>{
        const newArr = this.props.detail.mast[key].concat([`${data.cityNameEn}_${data.cityNameCn}`]);
        this.onChange(newArr, key);
      }
    })
  }

  handleEditDetailDestinationItem = (index, item) => {
    ScModal.open({
      state: 'edit',
      enKeyword: item.split('_')[0],
      success: (data)=>{
        let newArr = this.props.detail.mast.cities;
        newArr[index] = `${data.cityNameEn}_${data.cityNameCn}`;
        this.onChange(newArr, "cities");
      }
    })
  }

  handleDelDetailDestinationItem = (item) => {
    const newArr = global._.filter(this.props.detail.mast.cities, children=>{
      return children !== item;
    });
    this.onChange(newArr, 'cities');
  }

  handleDelDetailTraveller = (e, item) => {
    e.stopPropagation();
    const id = getMastId();
    const idText = `${Object.keys(id)[0]}=${Object.values(id)[0]}`;
    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.delelteTravellerById(item.id, idText).then(res => {
      if(requestSuccess(res)){
        const arr = global._.filter(this.props.detail.allMobileTravelerList, child => {
          return child.id !== item.id;
        });
        Toast.success('Success');
        this.props.dispatch({type: 'detail/changeDetail', payload: {
          allMobileTravelerList: arr
        }});
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)
  }

  onChange = (value, key) => {
    this.props.dispatch({type: 'detail/changeMast', payload: {
      [key]: value
    }});
  }

  render(){
    const hasPurposeOfTrip = this.props.showComponents.find(c => {return c.key == 'PurposeOfTripAndRemark'});
    return (
      <div className={styles.baseList}>
        <DatePicker
          visible={this.state.datepickerVisible}
          mode='date'
          onOk={this.handleSaveDatepickerValue}
          onDismiss={() => this.setState({ datepickerVisible: false })}
        />
        {
          this.props.edit
          ?
          <div className={`${styles.item} ${styles.blockItem}`}>
            <div className={styles.des}>*Destinations</div>
            <div className={styles.value}>
              {
                this.props.detail.mast.cities && this.props.detail.mast.cities.map((item, index) => {
                  return (
                    <div style={{width: '100%'}} key={item} onClick={()=>this.handleEditDetailDestinationItem(index, item)}>
                      {
                        index === 0
                        ?
                        <div>From(City)</div>
                        :
                        null
                      }
                      {
                        index === 1
                        ?
                        <div>To(City)</div>
                        :
                        null
                      }
                      <div className={styles.destinationItem} key={item}>
                        <div className={styles.destination}>{item}</div>
                        <div className={styles.action}>
                          <Button style={{width: '80px', margin: '5px'}} onClick={()=>this.handleDelDetailDestinationItem(item)}>Delete</Button>
                        </div>
                      </div>
                    </div>

                  )
                })
              }

              <Button style={{width: '150px', margin: '5px'}} onClick={() => this.handleShowCities('cities')}>
                {
                  this.props.detail.mast.cities && this.props.detail.mast.cities.length >= 1
                  ?
                  'Add(To City)'
                  :
                  'Add(From City)'
                }
              </Button>
            </div>
          </div>
          :
          <div className={styles.item}>
            <div className={styles.des}>*Destinations</div>
            <div className={styles.value}>
              <div className={styles.cities}>
                <div className={styles.textDes}>Departure City：</div>
                {
                  this.props.detail.mast && this.props.detail.mast.cities && this.props.detail.mast.cities[0]
                }
                <div className={styles.textDes}>Destination City：</div>
                {
                  this.props.detail.mast && this.props.detail.mast.cities ?
                  this.props.detail.mast.cities.filter((item, index) => index > 0).join('；')
                  :
                  null
                }
              </div>
            </div>
          </div>
        }
        <div className={styles.item}>
          <div className={styles.des}>Estimated Departure Date</div>
          <div className={styles.value} onClick={() => this.handleShowDatePicker('dptrDay')}>
              {(this.props.detail.mast.dptrDay && global.moment(this.props.detail.mast.dptrDay).format('YYYY-MM-DD') )|| 'Select'}
          </div>
        </div>
        <Picker disabled={!this.props.edit} data={this.handleListLabel(this.props.detail.expDptrDayStatusList)} cols={1} onChange={(values) => this.onChange(values[0], 'expDptrDayStatus')}>
          <div className={styles.item}>
            <div className={styles.des}>Estimated Departure Time Zone</div>
            <div className={styles.value}>
                {this.props.detail.mast.expDptrDayStatus || 'Select'}
            </div>
          </div>
        </Picker>
        {
          this.props.detail.mast.isOneWay == 'YES'
          ?
          null
          :
          <div className={styles.item}>
            <div className={styles.des}>Estimated Return Date</div>
            <div className={styles.value}  onClick={() => this.handleShowDatePicker('rtnDay')}>
              {(this.props.detail.mast.rtnDay && global.moment(this.props.detail.mast.rtnDay).format('YYYY-MM-DD')) || 'Select'}
            </div>
          </div>
        }
        {
          this.props.detail.mast.isOneWay == 'YES'
          ?
          null
          :
          <Picker disabled={!this.props.edit} data={this.handleListLabel(this.props.detail.expRtnDayStatusList)} cols={1} onChange={(values) => this.onChange(values[0], 'expRtnDayStatus')}>
            <div className={styles.item}>
              <div className={styles.des}>Estimated Return Time Zone</div>
              <div className={styles.value}>
                {this.props.detail.mast.expRtnDayStatus || 'Select'}
              </div>
            </div>
          </Picker>
        }
        {/*
          <div className={styles.item}>
            <div className={styles.des}>Requestor Remark</div>
            <div className={styles.value}>
              <InputItem
                clear
                disabled={!this.props.edit}
                placeholder="click input"
                value={this.props.detail.mast.requestorRemarks}
                onChange={(value) => this.onChange(value, 'requestorRemarks')}
              ></InputItem>
            </div>
          </div>
          */}

        <div className={`${styles.item} ${styles.blockItem}`}>
          <div className={styles.des}>Travellers(The first Traveller is travel leader)</div>
          <div className={styles.value}>
            <div className={styles.labels}>
              <div className={styles.label}>
                Traveller
              </div>
              <div className={styles.label}>
                Org Name
              </div>
              {
                this.props.edit || this.props.extraEditArr.find(item => item == 'UpdateWbsCode')
                ?
                <div className={styles.label}>
                  Action
                </div>
                :
                null
              }
            </div>
            <Accordion className={styles.cList} onChange={this.onChange}>
              {
                this.props.detail && this.props.detail.allMobileTravelerList && this.props.detail.allMobileTravelerList.map((item, index) => {
                  const headerDom = (cc) => {
                    return (
                      <div className={styles.headerValues}>
                        <div>{getNameByData(cc.empNo, this.props.detail.allMobileTravelerList, 'empInfo.employeeNo', 'empInfo.preferredName')}</div>
                        <div>{cc.orgName}</div>
                        {
                          this.props.extraEditArr.find(item => item == 'UpdateWbsCode')
                          ?
                          <div className={styles.smallDiv}>
                            <Button onClick={(e) => this.handleEditTravelerWbsCode(e, item, index)} style={{padding: '0px 5px'}}>Update</Button>
                          </div>
                          :
                          null
                        }
                        {
                          this.props.edit
                          ?
                          <div className={styles.smallDiv}>
                            <Button onClick={(e) => this.handleDelDetailTraveller(e, item)} style={{padding: '0px 5px'}}>Delete</Button>
                          </div>
                          :
                          null
                        }
                      </div>
                    )
                  }
                  return (
                    <Accordion.Panel header={headerDom(item)} key={index}>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Traveller</div>
                        <div className={styles.cValue}>{item.empNo} {getNameByData(item.empNo, this.props.detail.allMobileTravelerList, 'empInfo.employeeNo', 'empInfo.preferredName')}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Charge Employee</div>
                        <div className={styles.cValue}>{item.chargeEmpNo} {getNameByData(item.chargeEmpNo, this.props.detail.allMobileTravelerList, 'chargeEmpInfo.employeeNo', 'chargeEmpInfo.preferredName')}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Charge Cost Center</div>
                        <div className={styles.cValue}>{item.costCenter}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Org Name</div>
                      <div className={styles.cValue}>{item.orgName} {getNameByData(item.orgName, this.props.detail.allMobileTravelerList, 'orgName', 'chargeOrg.orgDesc')}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>WBS Code</div>
                        <div className={styles.cValue}>{item.wbsCode}</div>
                      </div>
                      {
                        this.props.detail.mast.isOutboundTrip && this.props.detail.mast.isOutboundTrip == 'YES'
                        ?
                        <div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Need Insurance</div>
                            <div className={styles.cValue}>{item.needInsurance}</div>
                          </div>
                          {
                            item.needInsurance == 'YES'
                            ?
                            <div className={styles.cItem}>
                              <div className={styles.cDes}>Gender</div>
                              <div className={styles.cValue}>{item.gender}</div>
                            </div>
                            :
                            null
                          }
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Name In Passport</div>
                            <div className={styles.cValue}>{item.nameInPassport}</div>
                          </div>
                          {
                            item.needInsurance == 'YES'
                            ?
                            <div className={styles.cItem}>
                              <div className={styles.cDes}>ID Type</div>
                              <div className={styles.cValue}>{item.idType}</div>
                            </div>
                            :
                            null
                          }
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>ID Number</div>
                            <div className={styles.cValue}>{item.idNumber}</div>
                          </div>
                          <div className={styles.cItem}>
                            <div className={styles.cDes}>Remark</div>
                            <div className={styles.cValue}>{item.remark}</div>
                          </div>
                        </div>
                        :
                        null
                      }
                    </Accordion.Panel>
                  )
                })
              }
            </Accordion>
            {
              !this.props.edit
              ?
              null
              :
              <Button style={{width: '150px', margin: '5px'}} onClick={this.handleAddTraveler}>Add</Button>
            }
          </div>
        </div>
        <div className={styles.item}>
          <div className={styles.des}>Travel Advance Needed</div>
          <div className={styles.value}>
            {/*needAdvance是被转化的值*/}
            {
              this.props.edit
              ?
                <Switch checked={this.props.detail.mast.needAdvance} onChange={(value) => this.onChange(value, 'needAdvance')}></Switch>
              :
                this.props.detail.mast.needAdvance ? 'YES':'NO'
            }
          </div>
        </div>
        {
          this.props.detail.mast.needAdvance
          ?
          <div className={`${styles.item} ${styles.blockItem}`}>
          <div className={styles.des}>Advance Info</div>
          <div className={styles.value}>
            <div className={styles.labels}>
              <div className={styles.label}>
                Advance No
              </div>
              <div className={styles.label}>
                Payee
              </div>
              <div className={styles.label}>
                Claim Amount
              </div>
              <div className={styles.label}>
                Currency
              </div>
            </div>
            <Accordion className={styles.cList} onChange={this.onChange}>
              {
                this.props.detail.mast && this.props.detail.advanceInfo && this.props.detail.advanceInfo.map((item, index) => {
                  const headerDom = (cc) => {
                    return (
                      <div className={styles.headerValues}>
                        <div>{cc.advanceNo}</div>
                        <div>{cc.payee}</div>
                        <div>{cc.claimAmt}</div>
                        <div>{cc.currency}</div>
                      </div>
                    )
                  }
                  return (
                    <Accordion.Panel header={headerDom(item)} key={index}>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Advance No</div>
                        <div className={styles.cValue}>{item.advanceNo}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Payee</div>
                        <div className={styles.cValue}>{item.payee}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Charge Employee</div>
                        <div className={styles.cValue}>{item.chargeEmployee}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Advance Date From</div>
                        <div className={styles.cValue}>{global.moment(item.adBeginDate).format('YYYY-MM-DD')}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Advance Date To</div>
                        <div className={styles.cValue}>{global.moment(item.adEndDate).format('YYYY-MM-DD')}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Claim Amount</div>
                        <div className={styles.cValue}>{item.claimAmt}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Currency</div>
                        <div className={styles.cValue}>{item.currency}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Exchange Rate Date</div>
                        <div className={styles.cValue}>{global.moment(item.exchangeRateDate).format('YYYY-MM-DD')}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Exchange Rate RMB</div>
                        <div className={styles.cValue}>{item.exchangeRMB}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Charge Cost Center</div>
                        <div className={styles.cValue}>{item.chargeCostCenter}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>RMB Equiv</div>
                        <div className={styles.cValue}>{(item.exchangeRMB * item.claimAmt).toFixed(2)}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Status</div>
                        <div className={styles.cValue}>{item.status}</div>
                      </div>
                      <div className={styles.cItem}>
                        <div className={styles.cDes}>Remark</div>
                        <div className={styles.cValue}>{item.remark}</div>
                      </div>
                    </Accordion.Panel>
                    )
                  })
                }
              </Accordion>
              {
                this.props.edit
                ?
                <Button style={{width: '150px', margin: '5px'}} onClick={this.handleAddAdvanceInfo}>Add</Button>
                :
                null
              }
            </div>
          </div>
          :
          null
        }
        {
          hasPurposeOfTrip
          ?
          null
          :
          <div>
            <div className={styles.item}>
              <div className={styles.des}>Purpose of trip</div>
              <div className={styles.value}>
                {this.props.detail.mast && this.props.detail.mast.purpose}
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>Type</div>
              <div className={styles.value}>
                {this.props.detail.mast && this.props.detail.mast.type}
              </div>
            </div>
            <div className={styles.item}>
              <div className={styles.des}>Visit Site</div>
              <div className={styles.value}>
                {/*subCompanys是被转化的值*/}
                {this.props.detail.mobileTrsSiteOffices && this.props.detail.mobileTrsSiteOffices.map(item => item.siteLocation + '；')}
              </div>
            </div>
          </div>
        }
      </div>
    )
  }
}


function mapStateToProps(state) {
  return {
    ...state.detail
  }
}
export default connect(mapStateToProps)(cTravelDetails);
